package personal.bean;

import java.io.StringReader;
import java.util.ArrayList;
import java.util.Calendar;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.model.SelectItem;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import resources.dao.AttendanceDAO;
import resources.dao.DepartmentDAO;
import resources.dao.EmployeeDAO;
import resources.pojo.pe_atnde;
import resources.pojo.pe_atnde_detl;
import resources.pojo.pe_atnde_dy;
import resources.pojo.pe_deptmt;
import resources.pojo.pe_eplye;
import resources.util.HVUtil;
import resources.util.Tool;

@ManagedBean(name = "attendanceManagement")
@SessionScoped
public class AttendanceManagement {
	private int month, year, days;
	private int selectedDepartment;

	ArrayList<Integer> listDay = new ArrayList<Integer>();
	ArrayList<pe_eplye> listEmployee;
	private ArrayList<pe_atnde_detl> listAttendance;
	private ArrayList<pe_atnde> allAttendance;
	private ArrayList<SelectItem> listDepartment;

	public void onloadNew() {
		if (!Tool.isPostBack()) {
			selectedDepartment = 1;
			initDate();
			HVUtil.open();
			listDepartment = DepartmentDAO.getSelectDepartment();
			HVUtil.close();
			view();
		}
	}

	private void initDate() {
		Calendar current = Calendar.getInstance();
		month = current.get(Calendar.MONTH);
		year = current.get(Calendar.YEAR);
	}

	public void save() {
		try {
			ArrayList<pe_atnde> list = new ArrayList<pe_atnde>();
			for (pe_atnde_detl detail : listAttendance) {
				pe_atnde attendance = new pe_atnde();
				attendance.setMh(month + 1);
				attendance.setYr(year);
				attendance.setPe_eplye(detail.getPe_eplye());
				attendance.setDa(XMLData(detail, month, year));
				list.add(attendance);
			}
			AttendanceDAO.save(list);
			Tool.message(Tool.getKey("data-saved"));
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void gotoAddNew() {
		try {
			Tool.redirect("add-new-attendance.html");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void setDay() {
		Calendar calendar = Calendar.getInstance();
		int date = 1;
		calendar.set(year, month, date);
		days = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
		listDay.clear();
		for (int i = 1; i <= days; i++)
			listDay.add(new Integer(i));
	}

	public void newListAttendance(ArrayList<pe_eplye> listEmp) {
		listAttendance = gListAttendance(listEmp, days, month, year);
	}

	public void view() {
		HVUtil.open();
		listAttendance = getListAttendanceDetail(month + 1, year,
				selectedDepartment, "");
		HVUtil.close();
	}

	private ArrayList<pe_atnde_detl> gListAttendance(
			ArrayList<pe_eplye> listEmp, int day, int month, int year) {
		ArrayList<pe_atnde_detl> list = new ArrayList<pe_atnde_detl>();

		for (pe_eplye emp : listEmp) {
			pe_atnde_detl temp = new pe_atnde_detl(day, month, year);
			temp.setPe_eplye(emp);
			list.add(temp);
		}
		return list;
	}

	private String XMLData(pe_atnde_detl detail, int month, int year) {
		String data = "<?xml version='1.0' encoding='UTF-8' ?><data>";
		try {

			data += "<info><employee-id>" + detail.getPe_eplye().getId()
					+ "</employee-id><month>" + month + 1 + "</month><year>"
					+ year + "</year></info>";
			for (int i = 0; i < days; i++) {
				data += "<day>";
				data += "<date>" + i + "</date>";
				data += "<type>" + detail.getListDay().get(i).getType()
						+ "</type>";
				data += "<start-time>"
						+ (detail.getListDay().get(i).getStartTime().length() == 0 ? "00:00"
								: detail.getListDay().get(i).getStartTime())
						+ "</start-time>";
				data += "<end-time>"
						+ (detail.getListDay().get(i).getEndTime().length() == 0 ? "00:00"
								: detail.getListDay().get(i).getEndTime())
						+ "</end-time>";
				data += "<description>"
						+ (detail.getListDay().get(i).getDescription().length() == 0 ? "..."
								: detail.getListDay().get(i).getDescription())
						+ "</description>";
				data += "</day>";
			}
			data += "</data>";
		} catch (NullPointerException e) {
			e.printStackTrace();
		}
		return data;
	}

	private ArrayList<pe_atnde_detl> getListAttendanceDetail(int month,
			int year, int depart, String idEmployee) {
		listAttendance = new ArrayList<pe_atnde_detl>();
		allAttendance = AttendanceDAO.getAttendance("selectByIDDepartment",
				month, year, "", depart);
		try {
			setDay();
			ArrayList<pe_eplye> lst = EmployeeDAO.getListEmployee(
					"getEmployeeAttendance", selectedDepartment, "", "");
			pe_atnde_detl item;
			pe_eplye emp;
			for (int i = 0; i < allAttendance.size(); i++) {
				item = new pe_atnde_detl();
				emp = allAttendance.get(i).getPe_eplye();
				item.setPe_eplye(emp);
				item.setListDay(getXMLData(allAttendance.get(i).getDa()));
				listAttendance.add(item);

				for (int y = 0; y < lst.size(); y++) {
					if (lst.get(y).getId().equals(emp.getId())) {
						lst.remove(y);
						y--;
					}
				}
			}

			listAttendance.addAll(gListAttendance(lst, days, month, year));

		} catch (Exception e) {
			e.printStackTrace();
		}
		return listAttendance;
	}

	private ArrayList<pe_atnde_dy> getXMLData(String xml) {
		ArrayList<pe_atnde_dy> temp = new ArrayList<pe_atnde_dy>();
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			InputSource is = new InputSource();
			is.setCharacterStream(new StringReader(xml));

			Document doc = db.parse(is);
			NodeList nodes = doc.getElementsByTagName("day");
			pe_atnde_dy item;
			for (int i = 0; i < nodes.getLength(); i++) {
				item = new pe_atnde_dy();
				Element element = (Element) nodes.item(i);

				NodeList type = element.getElementsByTagName("type");
				Element line = (Element) type.item(0);
				item.setType(getCharacterDataFromElement(line));

				NodeList starttime = element.getElementsByTagName("start-time");
				line = (Element) starttime.item(0);
				item.setStartTime(getCharacterDataFromElement(line));

				NodeList endtime = element.getElementsByTagName("end-time");
				line = (Element) endtime.item(0);
				item.setEndTime(getCharacterDataFromElement(line));

				NodeList description = element
						.getElementsByTagName("description");
				line = (Element) description.item(0);
				item.setDescription(getCharacterDataFromElement(line));

				temp.add(item);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return temp;
	}

	private String getCharacterDataFromElement(Element e) {
		Node child = e.getFirstChild();
		if (child instanceof CharacterData) {
			CharacterData cd = (CharacterData) child;
			return cd.getData();
		}
		return "?";
	}

	public ArrayList<pe_atnde_detl> getListAttendance() {
		return listAttendance;
	}

	public void setListAttendance(ArrayList<pe_atnde_detl> listAttendance) {
		this.listAttendance = listAttendance;
	}

	public void setYear(int year) {
		this.year = year;
	}

	public int getYear() {
		return year;
	}

	public void setMonth(int month) {
		this.month = month;
	}

	public int getMonth() {
		return month;
	}

	public ArrayList<Integer> getListDay() {
		return listDay;
	}

	public void setListDay(ArrayList<Integer> listDay) {
		this.listDay = listDay;
	}

	public void setAllAttendance(ArrayList<pe_atnde> allAttendance) {
		this.allAttendance = allAttendance;
	}

	public ArrayList<pe_atnde> getAllAttendance() {
		return allAttendance;
	}

	public void setListDepartment(ArrayList<SelectItem> listDepartment) {
		this.listDepartment = listDepartment;
	}

	public ArrayList<SelectItem> getListDepartment() {
		return listDepartment;
	}

	public void setSelectedDepartment(int selectedDepartment) {
		this.selectedDepartment = selectedDepartment;
	}

	public int getSelectedDepartment() {
		return selectedDepartment;
	}
}
